/**
 * 存储记录到缓存
 */
import {CookieUtils} from "@/utils/CookieUtils";

export class StorageUtils {
    /**
     * 存储信息到缓存
     * @param key
     * @param data
     * @param timeout
     */
    static addStorage(key: string, data: string, timeout=null) : void {
        CookieUtils.addCookie(key, data, timeout);
    }

    /**
     * 从缓存中获取记录
     * @param key
     */
    static getStorage(key: string): any {
        return new Promise((resolve, reject) => {
            resolve(CookieUtils.getCookie(key));
        })
    }

    static getStorage0(key: string): any {
        return CookieUtils.getCookie(key);
    }

    /**
     * 从存储中删除数据
     * @param key
     */
    static delStorage(key: string): void {
        CookieUtils.delCookie(key);
    }

    /**
     * 更新登录界面保留的登录信息的头像
     */
    static updateLoginRecord(avatarUrl: string): void {
        StorageUtils.addStorage("avatar_url", avatarUrl);
        StorageUtils.getStorage("loginname").then((loginname: any) => {
            StorageUtils.getStorage("login_records").then((records: any)=>{
                const loginOptions = JSON.parse(records) || [];
                const index = loginOptions.findIndex((item: any) => item.loginname === loginname);
                if (index > -1) {
                    loginOptions[index].avatarUrl = avatarUrl;
                    StorageUtils.addStorage('login_records', JSON.stringify(loginOptions));
                }
            })
        })
    }
}
